package com.example.springboot.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.springboot.mapper.UserMapper;
import com.example.springboot.pojo.User;
import com.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;


@Controller
public class UserController {

    @Autowired
    UserService userService;

    @Resource
    UserMapper userMapper;


    @RequestMapping("/index")
    public String index(String username, Integer enabled, Model model) {
        List<User> users = userService.query(username, enabled);
        for (User user : users){
            user.setRoles(userMapper.queryRolesByUid(user.getUid()));
        }
        model.addAttribute("users", users);
        model.addAttribute("username", username);
        model.addAttribute("enabled", enabled);
        return "index";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(Integer id) {
        User user = userService.queryById(id);
        Map<String, String> map = new HashMap<>();
        if (user.getEnabled()) {
            map.put("msg", "删除失败，只能删除禁用状态的用户");
        } else {
            int result = userService.del(id);
            map.put("msg", "删除成功");
        }
        return map;
    }

}
